//
//  JDGridTableViewCell.swift
//  DragonWallet
//
//  Created by volantPig on 2025/3/13.
//

import UIKit
import HXPhotoPicker

class JDGridTableViewCell: UITableViewCell {
    
    var playVideoVC: JDPlayVideoOrPictureViewController?
    
    var recruitModel: JDRecruitModel? {
        didSet {
            self.refreshData()
        }
    }
    
    private lazy var containerView: UIView = {
        let view = UIView()
        return view
    }()
    var contentLabel: UILabel?
    
    var gridCollectionView: UICollectionView?
    
    var middleLine: UIView?
    
    var authorInfoLabel: UILabel?
    var callAuthorButton: UIButton?
    var addDragonUnion: UIButton?
    
    var statusLabel: JDPaddingLabel?
    
    
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .none
        self.backgroundColor = .clear
        self.setupUIElements()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    
    func setupUIElements() {
        
        
        self.contentView.addSubview(containerView)
        containerView.snp.makeConstraints { make in
            make.leading.equalTo(self.contentView).offset(12)
            make.trailing.equalTo(self.contentView).offset(-12)
            make.top.equalTo(self.contentView)
            make.bottom.equalTo(self.contentView).offset(-10)
        }
        containerView.backgroundColor = color("#FFFFFF")
        containerView.layer.cornerRadius = 8
        
        
        self.contentLabel = UILabel()
        self.containerView.addSubview(self.contentLabel!)
        self.contentLabel?.snp.makeConstraints({ make in
            make.leading.equalTo(self.containerView).offset(16)
            make.trailing.equalTo(self.containerView).offset(-16)
            make.top.equalTo(self.containerView).offset(10)
        })
        self.contentLabel?.numberOfLines = 0
        self.contentLabel?.font = UIFont.systemFont(ofSize: 16, weight: .regular)
        self.contentLabel?.textColor = color("#333333")
        self.contentLabel?.text = "优质公建出租出售配套设施齐全，地角好，通!优质公建出租出售配套设施齐全，地角好，通!优质公建出租出售配套设施齐全，地角好，通!优质公建出租出售配套设施齐全，地角好，通!"


        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        
        self.gridCollectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        containerView.addSubview(self.gridCollectionView!)
        self.gridCollectionView?.snp.makeConstraints({ make in
            make.leading.equalTo(containerView).offset(16)
            make.top.equalTo(self.contentLabel!.snp.bottom).offset(15)
            make.trailing.equalTo(containerView).offset(-16)
//            make.height.equalTo(floor((UIScreen.main.bounds.size.width-44-20)/3.0))
            make.height.equalTo(floor((screenWidth-24-32-22)/3.0))
        })
        self.gridCollectionView?.delegate = self
        self.gridCollectionView?.dataSource = self
        self.gridCollectionView?.register(JDImageCollectionViewCell.self, forCellWithReuseIdentifier: "itemCell")
        
        self.statusLabel = JDPaddingLabel()
        self.containerView.addSubview(self.statusLabel!)
        self.statusLabel?.snp.makeConstraints { make in
            make.leading.equalTo(self.containerView).offset(16)
            make.top.equalTo(self.gridCollectionView!.snp.bottom).offset(10)
            make.height.equalTo(21)
        }
        self.statusLabel?.edgeInsets = UIEdgeInsets(top: 2, left: 4, bottom: 2, right: 4)
        self.statusLabel?.labelConfig(textAlignment: .center, font: UIFont.systemFont(ofSize: 12, weight: .regular), textColor: color("#333333"), numberOfLines: 1)
        self.statusLabel?.backgroundColor = color("#F5F6F8")
        self.statusLabel?.makeCorner(4)
        
        self.middleLine = UIView()
        self.containerView.addSubview(self.middleLine!)
        self.middleLine?.snp.makeConstraints { make in
            make.leading.equalTo(self.containerView).offset(12)
            make.trailing.equalTo(self.containerView).offset(-12)
//            make.top.equalTo(self.gridCollectionView!.snp.bottom).offset(10)
            make.top.equalTo(self.statusLabel!.snp.bottom).offset(10)
            make.height.equalTo(1)
        }
        self.middleLine?.backgroundColor = color("#EEEEEE")
        
        self.authorInfoLabel = UILabel()
        self.containerView.addSubview(self.authorInfoLabel!)
        self.authorInfoLabel?.snp.makeConstraints({ make in
            make.left.equalTo(self.containerView).offset(16)
            make.top.equalTo(self.middleLine!.snp.bottom)
            make.height.equalTo(50)
            make.bottom.equalTo(self.containerView)
        })
        self.authorInfoLabel?.text = "联系人：迟先生"
        self.authorInfoLabel?.textColor = color("#333333")
        self.authorInfoLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
    
        self.callAuthorButton = UIButton(type: .custom)
        self.containerView.addSubview(self.callAuthorButton!)
        self.callAuthorButton?.snp.makeConstraints({ make in
            make.left.equalTo(self.authorInfoLabel!.snp.right).offset(19)
            make.centerY.equalTo(self.authorInfoLabel!)
            make.size.equalTo(CGSize(width: 21, height: 21))
        })
        self.callAuthorButton?.setImage(UIImage(named: "call_image")?.withRenderingMode(.alwaysOriginal), for: .normal)
        self.callAuthorButton?.addTarget(self, action: #selector(callAuthorAction), for: .touchUpInside)
        
        self.addDragonUnion = UIButton(type: .custom)
        self.containerView.addSubview(self.addDragonUnion!)
        self.addDragonUnion?.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 7)
        self.addDragonUnion?.titleEdgeInsets = UIEdgeInsets(top: 0, left: 7, bottom: 0, right: 0)
        self.addDragonUnion?.snp.makeConstraints({ make in
            make.right.equalTo(self.containerView).offset(-12)
            make.centerY.equalTo(self.callAuthorButton!)
            make.width.equalTo(89)
        })
        self.addDragonUnion?.setTitle("邀加尨商圈", for: .normal)
        self.addDragonUnion?.setImage(UIImage(named: "add_DragonUnion"), for: .normal)
        self.addDragonUnion?.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .regular)
        self.addDragonUnion?.setTitleColor(color("#333333"), for: .normal)
//        self.addDragonUnion?.addTarget(self, action: #selector(addDragonUnionAction), for: .touchUpInside)
        
    }
    
    
    func refreshData() {
        print("打印:别问我是谁?")
        guard let confirmModel = self.recruitModel else { return }
        print("打印:查看2个数据:\(confirmModel.publishUserId)和\(JDLoginModel.default.userId)")
        
//        self.imgVOne?.kf.setImage(with: URL(string: JDImageBaseUrl + (confirmModel.picUrl1 ?? "")))
        self.contentLabel?.text = confirmModel.content
        self.authorInfoLabel?.text = "联系人：" + (confirmModel.contactName ?? "")
        
        if confirmModel.hadJoined ?? false {
          // 已加入
            self.addDragonUnion?.setImage(nil, for: .normal)
            self.addDragonUnion?.setTitle("已加入尨商圈", for: .normal)
            self.addDragonUnion?.removeTarget(self, action: #selector(addDragonUnionAction), for: .touchUpInside)
        } else {
            self.addDragonUnion?.setImage(UIImage(named: "add_DragonUnion"), for: .normal)
            self.addDragonUnion?.setTitle("邀加尨商圈", for: .normal)
            self.addDragonUnion?.addTarget(self, action: #selector(addDragonUnionAction), for: .touchUpInside)
        }
        
        if confirmModel.publishUserId == JDLoginModel.default.userId {
            self.addDragonUnion?.isHidden = true
        } else {
            self.addDragonUnion?.isHidden = false
        }
        
//        self.updateCustomConstraints(confirmModel)
        self.updateCollectionView(confirmModel)
        
        
        switch self.recruitModel?.publishStatus ?? -1 {
        case 0:
            self.statusLabel?.text = "待审核"
            self.statusLabel?.textColor = color("#333333")
            self.statusLabel?.backgroundColor = color("#F5F6F8")
        case 1:
            self.statusLabel?.text = "上架中"
            self.statusLabel?.textColor = color("#09926C")
            self.statusLabel?.backgroundColor = color("#DEF9F2")
        case 2:
            self.statusLabel?.text = "已结束"
            self.statusLabel?.textColor = color("#FA6161")
            self.statusLabel?.backgroundColor = color("#FFF2F2")
        case 3:
            self.statusLabel?.text = "违规下架"
            self.statusLabel?.textColor = color("#9DA1B2")
            self.statusLabel?.backgroundColor = color("#F5F6F8")
        default:
            self.statusLabel?.text = "状态异常"
            self.statusLabel?.textColor = color("#333333")
            self.statusLabel?.backgroundColor = color("#F5F6F8")
        }        
    }
    
    func updateCollectionView(_ currentModel: JDRecruitModel) {
        if (currentModel.videoUrl?.count ?? 0) > 0 && (currentModel.picUrl1?.count ?? 0) > 0 && (currentModel.picUrl2?.count ?? 0) > 0 && (currentModel.picUrl3?.count ?? 0) > 0 {
            // 2行
            self.gridCollectionView?.snp.updateConstraints({ make in
                make.height.equalTo(floor((screenWidth-24-32-22)/3.0)+11+floor((screenWidth-24-32-22)/3.0))
            })
        } else {
            // 1行
            self.gridCollectionView?.snp.updateConstraints({ make in
                make.height.equalTo(floor((screenWidth-24-32-22)/3.0))
            })
        }
        
        self.collectionViewDataSource.removeAll()
        if let videoUrl = currentModel.videoUrl, videoUrl.count > 0 {
            self.collectionViewDataSource.append(videoUrl)
        }
        if let imageUrl1 = currentModel.picUrl1, imageUrl1.count > 0 {
            self.collectionViewDataSource.append(imageUrl1)
        }
        if let imageUrl2 = currentModel.picUrl2, imageUrl2.count > 0 {
            self.collectionViewDataSource.append(imageUrl2)
        }
        if let imageUrl3 = currentModel.picUrl3, imageUrl3.count > 0 {
            self.collectionViewDataSource.append(imageUrl3)
        }
        
        self.gridCollectionView?.reloadData()
    
    }
    
    lazy var collectionViewDataSource: [String] = {
        let dataSource = [String]()
        return dataSource
        
    }()
    
    
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    
    
    @objc func loadImageWithIndexPath(_ currentIndex: IndexPath) {
        
        
        let currentItem = self.gridCollectionView?.cellForItem(at: currentIndex) as? JDImageCollectionViewCell
        
        // 这里需要把这个cell写成自定义的
        
        let videoUrl = self.recruitModel?.videoUrl ?? ""
        let url = self.collectionViewDataSource[currentIndex.row]
        if url == videoUrl {
            // 视频
            currentItem?.mainImageView.image = JDTools.getVideoThumbnail(url: URL(string: url)!)
        } else {
            // 图片
            if url.hasPrefix("http") {
                currentItem?.mainImageView.kf.setImage(with: URL(string: url))
            } else {
                currentItem?.mainImageView.downloadImage(url)
            }
        }
        
    }
    
}

// 拨打电话  和  邀加龙商圈
extension JDGridTableViewCell {
    @objc func callAuthorAction() {
        printLog("打电话\(self.recruitModel?.mobile)")
        
        let callStr = String.init(format: "tel:%@", self.recruitModel?.mobile ?? "")
        if let callUrl = URL(string: callStr) {
            UIApplication.shared.open(callUrl, options: [:]) { isSuccess in
            }
        }
    }
    
    @objc func addDragonUnionAction() {
        if !JDTools.checkToken() {
            return
        }
        let popupConfirmView = JDPopupConfirmView()
        popupConfirmView.confirmButtonSelected = { [weak self] in
            
            
            var params = [String: Any]()
            
            params["userId"] = self?.recruitModel?.publishUserId
            
            JDNetWorkRequest(.addDragonUnion(params)) { responseStr in
                
                let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
                if commonModel?.code == "0" {
                    JDSingle.default.needRefreshDragonCityUnion = true
                    // 成功
//                    self?.toast(message: "邀请成功")
                    NotificationCenter.default.post(name: NSNotification.Name.init("addDragonUnionSuccess"), object: nil)
                    JDTools.getKeyWindows()?.rootViewController?.view.toast(message: "邀请成功")
                    self?.changeaddDragonUnionState()
                } else {
                    JDTools.getKeyWindows()?.rootViewController?.view.toast(message: String.init(format: "%@", commonModel?.msg ?? ""))
                }
                
//            邀请加入龙商圈成功:{"returnMsg":"已邀请加入龙商圈","returnCode":"00","body":null}
                printLog("邀请加入龙商圈成功:\(responseStr)")
                
            } failure: { error in
                
                printLog("邀请加入龙商圈失败:\(error)")
                self?.toast(message: String.init(format: "%@", error.errorDescription ?? ""))
                
            } error: { errorCode in
                
                printLog("邀请加入龙商圈错误:\(errorCode)")
                self?.toast(message: String.init(format: "错误代码:%zd", errorCode))
            }

        }
        popupConfirmView.titleStr = String.init(format: "确定邀请 %@ 加入龙商圈吗？", self.recruitModel?.contactName ?? "")
        JDTools.getKeyWindows()?.rootViewController?.view.addSubview(popupConfirmView)
    }
    
    func changeaddDragonUnionState() {
        self.addDragonUnion?.setImage(nil, for: .normal)
        self.addDragonUnion?.setTitle("已加入尨商圈", for: .normal)
        
        guard let confirmModel = self.recruitModel else { return }
        confirmModel.hadJoined = true
    }
    
}


extension JDGridTableViewCell: UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.collectionViewDataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "itemCell", for: indexPath) as? JDImageCollectionViewCell
        
//        let imageV = UIImageView()
//        cell.contentView.addSubview(imageV)
//        imageV.snp.makeConstraints { make in
//            make.leading.trailing.top.bottom.equalToSuperview()
//        }
//        
        let videoUrl = self.recruitModel?.videoUrl ?? ""
        let url = self.collectionViewDataSource[indexPath.row]
        if url == videoUrl {
            cell?.isVideo()
            // 视频
//            imageV.image = JDTools.getVideoThumbnail(url: URL(string: url)!)
        } else {
//            // 图片
//            if url.hasPrefix("http") {
//                imageV.kf.setImage(with: URL(string: url))
//            } else {
//                imageV.downloadImage(url)
//            }
        }
        
        self.perform(#selector(loadImageWithIndexPath(_:)), with: indexPath, afterDelay: 0.1, inModes: [.default])
        
        return cell!
    }
        
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
//        return CGSize(width: floor((UIScreen.main.bounds.size.width-44-20)/3.0), height: floor((UIScreen.main.bounds.size.width-44-20)/3.0))
        return CGSize(width: floor((screenWidth-24-32-22-1)/3.0), height: floor((screenWidth-24-32-22-1)/3.0))
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: 0.001, left: 0.001, bottom: 0.001, right: 0.001)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 11
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 11
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("触发点击事件:\(indexPath.row)")
        
        
        let videoUrl = self.recruitModel?.videoUrl ?? ""
        let url = self.collectionViewDataSource[indexPath.row]
        if url == videoUrl && indexPath.row == 0 {
            // 视频
            print("看视频")
            self.playVideo()
        } else {
            // 图片
            let imageV = UIImageView()
            if url.hasPrefix("http") {
                imageV.kf.setImage(with: URL(string: url))
            } else {
                imageV.downloadImage(url)
            }
            // TODO: 这个地方，还是可以适当优化的
            self.showImage(imageV.image)
            print("看图片")
        }
    }
    
    @objc func playVideo() {
        self.playVideoVC = JDPlayVideoOrPictureViewController()
        self.playVideoVC?.playType = .video
        self.playVideoVC?.videoDataSource = [self.recruitModel?.videoUrl ?? ""]
        JDTools.getKeyWindows()?.addSubview(self.playVideoVC!.view)
    }
    
    @objc func showImage(_ image: UIImage?) {
        
        let style: UIModalPresentationStyle = .custom
        var config = HXPhotoPicker.PhotoBrowser.Configuration()
        config.showDelete = false
        config.modalPresentationStyle = style
        
        /// 显示图片浏览器
        /// - Parameters:
        ///   - previewAssets: 对应 PhotoAsset 的数组
        ///   - pageIndex: 当前预览的位置
        ///   - config: 相关配置
        ///   - fromVC: 来源控制器
        ///   - transitionalImage: 初始转场动画时展示的 UIImage
        ///   - transitionHandler: 转场过渡
        ///   - deleteAssetHandler: 删除资源
        ///   - longPressHandler: 长按事件
        /// - Returns: 对应的 PhotoBrowser
        
        guard let currentImg = image else { return }
        HXPhotoPicker.PhotoBrowser.show([PhotoAsset.init(localImageAsset: LocalImageAsset.init(currentImg))], pageIndex: 0, config: config, fromVC: nil, transitionalImage: nil, transitionHandler: nil, transitionCompletion: nil, deleteAssetHandler: nil, longPressHandler: nil)
        
        
//        HXPhotoPicker.PhotoBrowser.show([PhotoAsset.init(networkImageAsset: NetworkImageAsset.init(thumbnailURL: URL(string: "https://ww1.sinaimg.cn/mw690/717076a7gy1hse09y4a0pj21jk2bcqms.jpg"), originalURL: URL(string: "https://ww1.sinaimg.cn/mw690/717076a7gy1hse09y4a0pj21jk2bcqms.jpg")))], pageIndex: 0, config: config, fromVC: nil, transitionalImage: nil, transitionHandler: nil, transitionCompletion: nil, deleteAssetHandler: nil, longPressHandler: nil)
    }
    
    
    
}



